<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="数据库查询Document 对象有一个 objects 属性，用来访问在数据库中跟这个类有关的对象。这个 objects 属性其实是一个QuerySetManager ，它会创建和返回一个新的 QuerySet 对象的访问。这个 QuerySet 对象可以从数据库中遍历获取的文档： 123# Prints out the names of all the users in the database">
<meta name="keywords" content="MongoDB,Python,ORM">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoEngine 查询">
<meta property="og:url" content="https://l1xnan.gitee.io/posts/201807/62733.html">
<meta property="og:site_name" content="每天进步一点点">
<meta property="og:description" content="数据库查询Document 对象有一个 objects 属性，用来访问在数据库中跟这个类有关的对象。这个 objects 属性其实是一个QuerySetManager ，它会创建和返回一个新的 QuerySet 对象的访问。这个 QuerySet 对象可以从数据库中遍历获取的文档： 123# Prints out the names of all the users in the database">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-07-27T09:49:55.832Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoEngine 查询">
<meta name="twitter:description" content="数据库查询Document 对象有一个 objects 属性，用来访问在数据库中跟这个类有关的对象。这个 objects 属性其实是一个QuerySetManager ，它会创建和返回一个新的 QuerySet 对象的访问。这个 QuerySet 对象可以从数据库中遍历获取的文档： 123# Prints out the names of all the users in the database">






  <link rel="canonical" href="https://l1xnan.gitee.io/posts/201807/62733.html">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoEngine 查询 | 每天进步一点点</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">每天进步一点点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://l1xnan.gitee.io/posts/201807/62733.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="l1xnan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="每天进步一点点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoEngine 查询
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-07-16 02:02:22" itemprop="dateCreated datePublished" datetime="2018-07-16T02:02:22+08:00">2018-07-16</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-07-27 17:49:55" itemprop="dateModified" datetime="2018-07-27T17:49:55+08:00">2018-07-27</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/MongoDB/" itemprop="url" rel="index"><span itemprop="name">MongoDB</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="数据库查询"><a href="#数据库查询" class="headerlink" title="数据库查询"></a>数据库查询</h2><p><code>Document</code> 对象有一个 <code>objects</code> 属性，用来访问在数据库中跟这个类有关的对象。这个 <code>objects</code> 属性其实是一个<code>QuerySetManager</code> ，它会创建和返回一个新的 <code>QuerySet</code> 对象的访问。这个 <code>QuerySet</code> 对象可以从数据库中遍历获取的文档：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Prints out the names of all the users in the database</span></span><br><span class="line"><span class="keyword">for</span> user <span class="keyword">in</span> User.objects:</span><br><span class="line">    <span class="keyword">print</span> user.name</span><br></pre></td></tr></table></figure>

<h3 id="过滤查询"><a href="#过滤查询" class="headerlink" title="过滤查询"></a>过滤查询</h3><p>可以通过调用 <code>QuerySet</code> 对象的关键字参数来对数据查询进行过滤，关键字查询中的键和你想要查询的<code>Document</code> 中的字段一致：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># This will return a QuerySet that will only iterate over users whose</span></span><br><span class="line"><span class="comment"># 'country' field is set to 'uk'</span></span><br><span class="line">uk_users = User.objects(country=<span class="string">'uk'</span>)</span><br></pre></td></tr></table></figure>

<p>对于内嵌 document 的字段可以使用 <code>__</code> 来代替对象属性访问语法中的 <code>.</code> 进行访问：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># This will return a QuerySet that will only iterate over pages that have</span></span><br><span class="line"><span class="comment"># been written by a user whose 'country' field is set to 'uk'</span></span><br><span class="line">uk_pages = Page.objects(author__country=<span class="string">'uk'</span>)</span><br></pre></td></tr></table></figure>

<a id="more"></a>

<h3 id="查询操作符"><a href="#查询操作符" class="headerlink" title="查询操作符"></a>查询操作符</h3><p>在查询中也可以使用操作符，只要将其加在关键字的双下划线之后即可：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Only find users whose age is 18 or less</span></span><br><span class="line">young_users = Users.objects(age__lte=<span class="number">18</span>)</span><br></pre></td></tr></table></figure>

<p>可用的运算符如下：</p>
<ul>
<li><code>ne</code> – 不等于<code>≠</code></li>
<li><code>lt</code> – 小于<code>&lt;</code></li>
<li><code>lte</code> – 小于等于<code>≤</code></li>
<li><code>gt</code> – 大于<code>&gt;</code></li>
<li><code>gte</code> – 大于等于 <code>≥</code></li>
<li><code>not</code> – 否定一个标准的检查，需要用在其他操作符之前(e.g. <code>Q(age__not__mod=5)</code>)</li>
<li><code>in</code> – 值在 <code>list</code> 中</li>
<li><code>nin</code> – 值不在 <code>list</code> 中</li>
<li><code>mod</code> – <code>value % x == y</code>, 其中  <code>x</code>  和 <code>y</code>  为给定的值</li>
<li><code>all</code> – <code>list</code> 里面所有的值</li>
<li><code>size</code> – 数组的大小</li>
<li><code>exists</code> – 存在这个值</li>
</ul>
<h4 id="字符串查询"><a href="#字符串查询" class="headerlink" title="字符串查询"></a>字符串查询</h4><p>以下操作符可以快捷的进行正则查询：</p>
<ul>
<li><code>exact</code> – 字符串型字段完全匹配这个值</li>
<li><code>iexact</code> – 字符串型字段完全匹配这个值（大小写敏感）</li>
<li><code>contains</code> – 字符串字段包含这个值</li>
<li><code>icontains</code> – 字符串字段包含这个值（大小写敏感）</li>
<li><code>startswith</code> – 字符串字段由这个值开头</li>
<li><code>istartswith</code> – 字符串字段由这个值开头（大小写敏感）</li>
<li><code>endswith</code> – 字符串字段由这个值结尾</li>
<li><code>iendswith</code> – 字符串字段由这个值结尾（大小写敏感）</li>
<li><code>match</code> – 执行 <code>$elemMatch</code> 操作，所以你可以使用一个数组中的 document 实例</li>
</ul>
<h4 id="地理查询"><a href="#地理查询" class="headerlink" title="地理查询"></a>地理查询</h4><p>PASS</p>
<h4 id="列表查询"><a href="#列表查询" class="headerlink" title="列表查询"></a>列表查询</h4><p>对于大多数字段，这种语法会查询出那些字段与给出的值相匹配的 document，但是当一个字段引用 <code>ListField</code> 的时候，而只会提供一条数据，那么包含这条数据的就会被匹配上：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Page</span><span class="params">(Document)</span>:</span></span><br><span class="line">    tags = ListField(StringField())</span><br><span class="line"></span><br><span class="line"><span class="comment"># This will match all pages that have the word 'coding' as an item in the</span></span><br><span class="line"><span class="comment"># 'tags' list</span></span><br><span class="line">Page.objects(tags=<span class="string">'coding'</span>)</span><br></pre></td></tr></table></figure>

<h4 id="原始查询"><a href="#原始查询" class="headerlink" title="原始查询"></a>原始查询</h4><p>你可以通过 <code>__raw__</code> 参数来使用一个原始的 <code>PyMongo</code> 语句来进行查询，这样可以进行原始的完整查询：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Page.objects(__raw__=&#123;<span class="string">'tags'</span>: <span class="string">'coding'</span>&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="限制和跳过结果"><a href="#限制和跳过结果" class="headerlink" title="限制和跳过结果"></a>限制和跳过结果</h3><p>就像传统的 ORM 一样，你有时候需要限制返回的结果的数量，或者需要跳过一定数量的结果。<code>QuerySet</code> 里面可以使用 <code>limit()</code> 和 <code>skip()</code> 这两个方法来实现，但是更推荐使用数组切割的语法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Only the first 5 people</span></span><br><span class="line">users = User.objects[:<span class="number">5</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># All except for the first 5 people</span></span><br><span class="line">users = User.objects[<span class="number">5</span>:]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 5 users, starting from the 11th user found</span></span><br><span class="line">users = User.objects[<span class="number">10</span>:<span class="number">15</span>]</span><br></pre></td></tr></table></figure>

<p>你可以指定让查询返回一个结果。如果这个条在数据库中不存在，那么会引发 <code>IndexError</code> 错误 。使用 <code>first()</code> 方法在数据不存在的时候会返回 <code>None</code>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># Make sure there are no users</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>User.drop_collection()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>User.objects[<span class="number">0</span>]</span><br><span class="line">IndexError: list index out of range</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>User.objects.first() == <span class="literal">None</span></span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>User(name=<span class="string">'Test User'</span>).save()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>User.objects[<span class="number">0</span>] == User.objects.first()</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>

<h3 id="默认Document-查询"><a href="#默认Document-查询" class="headerlink" title="默认Document 查询"></a>默认<code>Document</code> 查询</h3><p>默认情况下，<code>Document</code>的<code>objects</code> 属性返回一个一个 <code>QuerySet</code> 对象，它并没有进行任何筛选和过滤，它返回的是所有的数据对象。这一点可以通过给一个 <code>document</code> 定义一个方法来修改 一个<code>queryset</code> 。这个方法需要两参数<code>__doc_cls</code> 和 <code>queryset</code> 。第一个参数是定义这个方法的 <code>Document</code> 类名（从这个意义上来说，这个方法像是一个 <code>classmethod()</code> 而不是一般的方法），第二个参数是初始化的 <code>queryset</code>。这个方法需要使用 <code>queryset_manager()</code>来装饰来它，使得它被认可。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BlogPost</span><span class="params">(Document)</span>:</span></span><br><span class="line">    title = StringField()</span><br><span class="line">    date = DateTimeField()</span><br><span class="line"></span><br><span class="line"><span class="meta">    @queryset_manager</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">objects</span><span class="params">(doc_cls, queryset)</span>:</span></span><br><span class="line">        <span class="comment"># This may actually also be done by defining a default ordering for</span></span><br><span class="line">        <span class="comment"># the document, but this illustrates the use of manager methods</span></span><br><span class="line">        <span class="keyword">return</span> queryset.order_by(<span class="string">'-date'</span>)</span><br></pre></td></tr></table></figure>

<p>你不用调用 <code>objects</code> 方法，你可以自定义更多的管理方法，例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BlogPost</span><span class="params">(Document)</span>:</span></span><br><span class="line">    title = StringField()</span><br><span class="line">    published = BooleanField()</span><br><span class="line"></span><br><span class="line"><span class="meta">    @queryset_manager</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">live_posts</span><span class="params">(doc_cls, queryset)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> queryset.filter(published=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">BlogPost(title=<span class="string">'test1'</span>, published=<span class="literal">False</span>).save()</span><br><span class="line">BlogPost(title=<span class="string">'test2'</span>, published=<span class="literal">True</span>).save()</span><br><span class="line"><span class="keyword">assert</span> len(BlogPost.objects) == <span class="number">2</span></span><br><span class="line"><span class="keyword">assert</span> len(BlogPost.live_posts()) == <span class="number">1</span></span><br></pre></td></tr></table></figure>

<h3 id="自定义-QuerySets"><a href="#自定义-QuerySets" class="headerlink" title="自定义 QuerySets"></a>自定义 QuerySets</h3><p>当你想自己定义一些方法来过滤 <code>document</code> 的时候，继承 <code>QuerySet</code> 类对你来说就是个好的方法。为了在 <code>document</code> 里面使用一个自定义的 <code>QuerySet</code> 类，你可以在 <code>document</code> 里的 <code>meta</code> 字典里设置 <code>queryset_class</code> 的值来实现它。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AwesomerQuerySet</span><span class="params">(QuerySet)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_awesome</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.filter(awesome=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Page</span><span class="params">(Document)</span>:</span></span><br><span class="line">    meta = &#123;<span class="string">'queryset_class'</span>: AwesomerQuerySet&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># To call:</span></span><br><span class="line">Page.objects.get_awesome()</span><br></pre></td></tr></table></figure>

<h3 id="Aggregation-聚合"><a href="#Aggregation-聚合" class="headerlink" title="Aggregation 聚合"></a>Aggregation 聚合</h3><p>MongoDB 提供了开箱即用的聚合方法，但没有 RDBMS 提供的那样多。MongoEngine 提供了一个包装过的内置的方法，同时自身提供了一些方法，它实现了在数据库服务上执行的 Javascript 代码的功能。</p>
<h4 id="结果计数"><a href="#结果计数" class="headerlink" title="结果计数"></a>结果计数</h4><p>就像限制和跳过结果一样， <code>QuerySet</code> 对象提供了用来计数的方法 - <code>count()</code>，不过还有一个更 <code>Pythonic</code> 的方法来实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">num_users = len(User.objects)</span><br></pre></td></tr></table></figure>

<h4 id="更多功能"><a href="#更多功能" class="headerlink" title="更多功能"></a>更多功能</h4><p>当你想为 <code>document</code> 的特定的字段的数量计数的时候，可以使用 <code>sum()</code>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yearly_expense = Employee.objects.sum(<span class="string">'salary'</span>)</span><br></pre></td></tr></table></figure>

<p>当你想求某个字段的平均值的时候，可以使用 <code>average()</code>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mean_age = User.objects.average(<span class="string">'age'</span>)</span><br></pre></td></tr></table></figure>

<p>MongoEngine 提供了一个方法来获取一个在集合里 <code>item</code> 的频率 - <code>item_frequencies()</code>。下面一个例子可以生成 <code>tag-clouds</code>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Article</span><span class="params">(Document)</span>:</span></span><br><span class="line">    tag = ListField(StringField())</span><br><span class="line"></span><br><span class="line"><span class="comment"># After adding some tagged articles...</span></span><br><span class="line">tag_freqs = Article.objects.item_frequencies(<span class="string">'tag'</span>, normalize=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> itemgetter</span><br><span class="line">top_tags = sorted(tag_freqs.items(), key=itemgetter(<span class="number">1</span>), reverse=<span class="literal">True</span>)[:<span class="number">10</span>]</span><br></pre></td></tr></table></figure>

<h3 id="查询效率和性能"><a href="#查询效率和性能" class="headerlink" title="查询效率和性能"></a>查询效率和性能</h3><p>PASS</p>
<h3 id="高级查询"><a href="#高级查询" class="headerlink" title="高级查询"></a>高级查询</h3><p>有时候使用关键字参数返回的 <code>QuerySet</code> 不能完全满足你的查询需要。例如有时候你需要将约束条件进行<code>and</code>，<code>or</code> 的操作。你可以使用 MongoEngine 提供的 <code>Q</code> 类来实现，一个 <code>Q</code> 类代表了一个查询的一部分，里面的参数设置与你查询<code>document</code> 的时候相同。建立一个复杂查询的时候，你需要用 <code>&amp;</code> 或 <code>|</code> 操作符将 <code>Q</code> 对象连结起来。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> mongoengine.queryset.visitor <span class="keyword">import</span> Q</span><br><span class="line"></span><br><span class="line"><span class="comment"># Get published posts</span></span><br><span class="line">Post.objects(Q(published=<span class="literal">True</span>) | Q(publish_date__lte=datetime.now()))</span><br><span class="line"></span><br><span class="line"><span class="comment"># Get top posts</span></span><br><span class="line">Post.objects((Q(featured=<span class="literal">True</span>) &amp; Q(hits__gte=<span class="number">1000</span>)) | Q(hits__gte=<span class="number">5000</span>))</span><br></pre></td></tr></table></figure>

<h3 id="Atomic-updates（原子更新）"><a href="#Atomic-updates（原子更新）" class="headerlink" title="Atomic updates（原子更新）"></a>Atomic updates（原子更新）</h3><p><code>MongoDB 文档</code> 可以通过<code>QuerySet</code> 上的 <code>update_one()</code>、<code>update()</code>、<code>modify()</code> 方法自动更新。下面几种操作符可以被用到这几种方法上：</p>
<ul>
<li><code>set</code> – 设置成一个指定的值</li>
<li><code>unset</code> – 删除一个指定的值</li>
<li><code>inc</code> – 将值加上一个给定的数</li>
<li><code>dec</code> – 将值减去一个给定的数</li>
<li><code>push</code> – 在 <code>list</code> 中添加一个值</li>
<li><code>push_all</code> – 在 <code>list</code> 中添加一个值</li>
<li><code>pop</code> – 移除<code>list</code> 的第一项或最后一项（根据 <code>pop__&lt;field&gt;=val</code> 中<code>val</code> 的值决定删除第一项还是最后一项，一般情况下，<code>val</code> 为负则删除第一项，为正则删除最后一项，参见：<a href="http://docs.mongodb.org/manual/reference/operator/update/pop/" target="_blank" rel="noopener">mongodb $pop</a></li>
<li><code>pull</code> – 从 <code>list</code> 里面移除一个值</li>
<li><code>pull_all</code> – 从 <code>list</code> 里面移除个值</li>
<li><code>add_to_set</code> – 当要添加的值不在 <code>list</code> 中时，添加这个值</li>
</ul>
<p>原子更新的语法类似于查询语法，区别在于修饰操作符位于字段之前，而不是之后：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>post = BlogPost(title=<span class="string">'Test'</span>, page_views=<span class="number">0</span>, tags=[<span class="string">'database'</span>])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.save()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>BlogPost.objects(id=post.id).update_one(inc__page_views=<span class="number">1</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.reload()  <span class="comment"># the document has been changed, so we need to reload it</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.page_views</span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>BlogPost.objects(id=post.id).update_one(set__title=<span class="string">'Example Post'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.reload()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.title</span><br><span class="line"><span class="string">'Example Post'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>BlogPost.objects(id=post.id).update_one(push__tags=<span class="string">'nosql'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.reload()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>post.tags</span><br><span class="line">[<span class="string">'database'</span>, <span class="string">'nosql'</span>]</span><br></pre></td></tr></table></figure>

<p>如果没有修饰操作符，则默认为<code>$set</code>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">BlogPost.objects(id=post.id).update(title=<span class="string">'Example Post'</span>)</span><br><span class="line">BlogPost.objects(id=post.id).update(set__title=<span class="string">'Example Post'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="服务器端-JavaScript-执行"><a href="#服务器端-JavaScript-执行" class="headerlink" title="服务器端 JavaScript 执行"></a>服务器端 JavaScript 执行</h3><p>可以写 Javascript 函数，然后发送到服务器来执行。它返回结果是 Javascript 函数的返回值。这个功能是通过<code>QuerySet()</code>对象的<code>exec_js()</code> 方法实现。传递一个包含一个 Javascript 函数的字符串作为第一个参数。</p>
<p>其余位置的参数的名字字段将作为您的 Javascript 函数的参数传递过去。</p>
<p>在 JavaScript 函数范围中，一些变量可用：</p>
<ul>
<li><code>collection</code> – 对应使用的 <code>Document</code> 类的集合的名称</li>
<li><code>query</code> – 一个  <code>QuerySet</code> 对象</li>
<li><code>options</code> – 一个对象，它包含要传递给 <code>exec_js()</code> 函数的一些参数</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sum_field</span><span class="params">(document, field_name, include_negatives=True)</span>:</span></span><br><span class="line">    code = <span class="string">"""</span></span><br><span class="line"><span class="string">    function(sumField) &#123;</span></span><br><span class="line"><span class="string">        var total = 0.0;</span></span><br><span class="line"><span class="string">        db[collection].find(query).forEach(function(doc) &#123;</span></span><br><span class="line"><span class="string">            var val = doc[sumField];</span></span><br><span class="line"><span class="string">            if (val &gt;= 0.0 || options.includeNegatives) &#123;</span></span><br><span class="line"><span class="string">                total += val;</span></span><br><span class="line"><span class="string">            &#125;</span></span><br><span class="line"><span class="string">        &#125;);</span></span><br><span class="line"><span class="string">        return total;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    options = &#123;<span class="string">'includeNegatives'</span>: include_negatives&#125;</span><br><span class="line">    <span class="keyword">return</span> document.objects.exec_js(code, field_name, **options)</span><br></pre></td></tr></table></figure>


      
    </div>

    

    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>l1xnan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://l1xnan.gitee.io/posts/201807/62733.html" title="MongoEngine 查询">https://l1xnan.gitee.io/posts/201807/62733.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" rel="tag"># MongoDB</a>
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/ORM/" rel="tag"># ORM</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/201807/11156.html" rel="next" title="好用的命令行软件">
                <i class="fa fa-chevron-left"></i> 好用的命令行软件
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/201807/15308.html" rel="prev" title="Python 命令行神器 Click（一）快速上手">
                Python 命令行神器 Click（一）快速上手 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">l1xnan</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">43</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">14</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/l1xnan" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i></a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.yuque.com/l1xnan" target="_blank" title="语雀"><i class="fa fa-fw fa-crow"></i></a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#数据库查询"><span class="nav-number">1.</span> <span class="nav-text">数据库查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#过滤查询"><span class="nav-number">1.1.</span> <span class="nav-text">过滤查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询操作符"><span class="nav-number">1.2.</span> <span class="nav-text">查询操作符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串查询"><span class="nav-number">1.2.1.</span> <span class="nav-text">字符串查询</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#地理查询"><span class="nav-number">1.2.2.</span> <span class="nav-text">地理查询</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#列表查询"><span class="nav-number">1.2.3.</span> <span class="nav-text">列表查询</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原始查询"><span class="nav-number">1.2.4.</span> <span class="nav-text">原始查询</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#限制和跳过结果"><span class="nav-number">1.3.</span> <span class="nav-text">限制和跳过结果</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#默认Document-查询"><span class="nav-number">1.4.</span> <span class="nav-text">默认Document 查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义-QuerySets"><span class="nav-number">1.5.</span> <span class="nav-text">自定义 QuerySets</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Aggregation-聚合"><span class="nav-number">1.6.</span> <span class="nav-text">Aggregation 聚合</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#结果计数"><span class="nav-number">1.6.1.</span> <span class="nav-text">结果计数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#更多功能"><span class="nav-number">1.6.2.</span> <span class="nav-text">更多功能</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询效率和性能"><span class="nav-number">1.7.</span> <span class="nav-text">查询效率和性能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#高级查询"><span class="nav-number">1.8.</span> <span class="nav-text">高级查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Atomic-updates（原子更新）"><span class="nav-number">1.9.</span> <span class="nav-text">Atomic updates（原子更新）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器端-JavaScript-执行"><span class="nav-number">1.10.</span> <span class="nav-text">服务器端 JavaScript 执行</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">l1xnan</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.9.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a> v6.3.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  


  
  

  

  

  

  

  

</body>
</html>
